//
//  LPQuestionItemView.m
//  muce
//
//  Created by Pan on 2018/3/19.
//  Copyright © 2018年  yunshao. All rights reserved.
//

/** 问题项 */

#import "LPQuestionItemView.h"
#import "pch.h"
#import "LPSortOptionView.h"


#define WIDTH CGRectGetWidth(self.frame)
#define HEIGHT CGRectGetHeight(self.frame)
#define TAG_SelectButton 2134
#define TAG_SortView 5555
#define ASCII_A 65

@interface LPQuestionItemView ()<UITextViewDelegate>

@property (nonatomic, strong) NSMutableDictionary *dictioanry;
@property (nonatomic, assign) questionType questionType;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, assign) CGFloat offsetY;
@property (nonatomic, strong) UILabel *titleLabel;
/** 选择题参数 */
@property (nonatomic, strong) UIButton *selectButton;                   // 当前选中按钮

/** 拖动排序使用属性 */
@property (nonatomic, assign) CGPoint lastPoint;
@property (nonatomic, strong) LPSortOptionView *beforeSortView;         // 前一个view
@property (nonatomic, strong) LPSortOptionView *contentSortView;        // 选中的Veiw
@property (nonatomic, strong) LPSortOptionView *afterSortView;          // 后一个view
@property (nonatomic, assign) CGPoint beforeOrigin;                     //
@property (nonatomic, assign) CGPoint contentOrigin;                    //
@property (nonatomic, assign) CGPoint afterOrigin;                      //

@end

@implementation LPQuestionItemView

- (instancetype)initWithFrame:(CGRect)frame dictionary:(NSDictionary *)dictionary questionIndex:(NSInteger)questionIndex {
    
    if (self = [super initWithFrame:frame]) {
        _dictioanry = (NSMutableDictionary *)dictionary;
        _questionIndex = questionIndex;
        
        // 初始化回答内容
        [self initAnswerDictionary];
        // 加载UI
        [self createUI];
        // 填充内容（上次提交数据）
        [self fillContent];
    }
    
    return self;
}

- (void)initAnswerDictionary {
    if (!self.answerDictionary) {
        self.answerDictionary = [NSMutableDictionary dictionary];
        [self.answerDictionary setObject:_dictioanry[@"paper_id"] forKey:@"paper_id"];
        [self.answerDictionary setObject:_dictioanry[@"question_id"] forKey:@"question_id"];
        [self.answerDictionary setObject:_dictioanry[@"section_id"] forKey:@"section_id"];
    }
}

///** 懒加载初始化 */
//- (void)setAnswerDictionary:(NSMutableDictionary *)answerDictionary {
//
//}

- (void)createUI {
    
    // 判断题型
    if ([_dictioanry[@"section_id"] integerValue] == 150) {
        // 单选题
        _questionType = questionType_singleChoice;
    }else if ([_dictioanry[@"section_id"] integerValue] == 151) {
        // 多选题
        _questionType = questionType_multipleChoie;
    }else if ([_dictioanry[@"section_id"] integerValue] == 152) {
        // 拖动排序
        _questionType = questionType_sortingProblem;
        self.sortViewArray = [NSMutableArray array];
    }else if ([_dictioanry[@"section_id"] integerValue] == 153) {
        // 简答题
        _questionType = questionType_shortAnswer;
    }else {
        // 未知类型中断
        return;
    }
   
    NSString *titleStr = [NSString stringWithFormat:@"%ld.%@（%@）", self.questionIndex + 1, _dictioanry[@"list"][@"question_name"], _dictioanry[@"sectionName"]];
    
    // 问题标题
    _titleLabel = [self addLableWithMaxWidth:WIDTH - DSFixedPX(40) * 2 height:999 string:titleStr font:DSFontSize(16) textColor:DSColorWithHex(0x333333) numberOfLines:0 sizfTofit:YES];
    _titleLabel.center = CGPointMake(DSFixedPX(40) + CGRectGetWidth(_titleLabel.frame) / 2.0, CGRectGetHeight(_titleLabel.frame) / 2.0);
    [self addSubview:_titleLabel];

    _offsetY = CGRectGetMaxY(_titleLabel.frame);
    
    // 问题选项
    if (_questionType == questionType_shortAnswer) {
        // 简答
        [self addShortAnswerTextView];
    }else {
        for (int i = 0; i < [_dictioanry[@"list"][@"list"] count]; i++) {
            if (_questionType == questionType_sortingProblem) {
                // 排序题
                [self addSortingOptionViewIndex:i];
            }else {
                // 单选\多选
                [self addSelectOptionsViewIndex:i];
            }
        }
    }
    
    // 默认排序答案
    if (_questionType == questionType_sortingProblem) {
        [self setSortAnswer];
    }
    
    // 重置大小
    CGRect rect = self.frame;
    rect.size.height = _offsetY;
    self.frame = rect;
}

/** 单选\多选 选项 */
- (void)addSelectOptionsViewIndex:(NSInteger)index {
    
    NSDictionary *optionDic = _dictioanry[@"list"][@"list"][index];
    if (!optionDic) {
        return;
    }
    
    // 选框
    UIButton *selectButton = [[UIButton alloc] initWithFrame:CGRectZero];
    if (self.questionType == questionType_singleChoice) {
        [selectButton setImage:[UIImage imageNamed:@"selectButtonSingle"] forState:UIControlStateNormal];
        [selectButton setImage:[UIImage imageNamed:@"selectButtonSingle_b"] forState:UIControlStateSelected];
    }else if (self.questionType == questionType_multipleChoie) {
        [selectButton setImage:[UIImage imageNamed:@"selectButtonMulti"] forState:UIControlStateNormal];
        [selectButton setImage:[UIImage imageNamed:@"selectButtonMulti_b"] forState:UIControlStateSelected];
    }

    [selectButton sizeToFit];
    selectButton.tag = index + TAG_SelectButton;
    selectButton.userInteractionEnabled = YES;
    selectButton.center = CGPointMake(DSFixedPX(100) + CGRectGetWidth(selectButton.frame) / 2.0, _offsetY + DSFixedPX(40) + CGRectGetHeight(selectButton.frame) / 2.0);
    [selectButton addTarget:self action:@selector(selectButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:selectButton];
    
    // 选项
    UILabel *optionLabel = [self addLableWithMaxWidth:WIDTH - CGRectGetMaxX(selectButton.frame) - DSFixedPX(40) * 2 height:999 string:[NSString stringWithFormat:@"%@.%@",optionDic[@"option_name"],optionDic[@"option_content"]] font:DSFontSize(16) textColor:DSColorWithHex(0x333333) numberOfLines:0 sizfTofit:YES];
    optionLabel.center = CGPointMake(CGRectGetMaxX(selectButton.frame) + DSFixedPX(25) + CGRectGetWidth(optionLabel.frame) / 2.0, CGRectGetMinY(selectButton.frame) + CGRectGetHeight(optionLabel.frame) / 2.0 + DSFixedPX(2));
    [self addSubview:optionLabel];
    
    _offsetY = CGRectGetMaxY(selectButton.frame);
}

/** 排序项 */
- (void)addSortingOptionViewIndex:(NSInteger)index {
    
    // 选项
    LPSortOptionView *sortView = [[LPSortOptionView alloc] initWithFrame:CGRectMake(DSFixedPX(40), _offsetY + DSFixedPX(20), WIDTH - DSFixedPX(40) * 2.0, 999) dictionary:_dictioanry[@"list"][@"list"][index] index:index];
    sortView.tag = TAG_SortView + index;
    [self addSubview:sortView];
    
    UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longGestureSortingOptionView:)];
    [sortView addGestureRecognizer:longGesture];
    
    // 添加数据排序
    [self.sortViewArray addObject:sortView];
    
    _offsetY = CGRectGetMaxY(sortView.frame);
}

/** 简答输入框 */
- (void)addShortAnswerTextView {
    
    if (!_textView) {
        _textView = [[UITextView alloc] initWithFrame:CGRectMake(DSFixedPX(40), _offsetY + DSFixedPX(25), WIDTH - DSFixedPX(40) * 2, DSFixedPX(380))];
        _textView.layer.borderWidth = DSFixedPX(2);
        _textView.layer.borderColor = DSColorWithHex(0x6aa2e0).CGColor;
        _textView.textColor = DSColorWithHex(0x333333);
        _textView.font = DSFontSize(14);
        _textView.delegate = self;
        [self addSubview:_textView];
        
        _offsetY = CGRectGetMaxY(_textView.frame);
    }
}

/** Label标签 */
-(UILabel *)addLableWithMaxWidth:(CGFloat)maxWidth
                          height:(CGFloat)height
                          string:(NSString *)string
                            font:(UIFont *)font
                       textColor:(UIColor *)textColor
                   numberOfLines:(int)numberOfLines
                       sizfTofit:(BOOL)sizfTofit
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, maxWidth, height)];
    if ([string isKindOfClass:[NSNull class]]) {
        string = @"";
    }
    if (string.length <= 0) {
        string = @"";
    }
    label.text = string;
    
    label.font = font;
    label.backgroundColor = [UIColor clearColor];
    label.textColor = textColor;
    label.numberOfLines = numberOfLines;
    [label sizeToFit];
    if (sizfTofit) {
        if (CGRectGetWidth(label.bounds) > maxWidth) {
            label.bounds = CGRectMake(0, 0, maxWidth, CGRectGetHeight(label.bounds));
        }
    }else{
        label.bounds = CGRectMake(0, 0, maxWidth, height);
    }
    return label;
}

#pragma mark ============================= 选择题 ==============================
- (void)selectButtonClick:(UIButton *)sender {
    
    if (self.questionType == questionType_singleChoice) {
        // 单选题
        _selectButton.selected = NO;
        _selectButton = sender;
        _selectButton.selected = YES;
        [self.answerDictionary setObject:_dictioanry[@"list"][@"list"][sender.tag - TAG_SelectButton][@"option_name"] forKey:@"answer"];
    }else if (questionType_multipleChoie) {
        // 多选题
        sender.selected = !sender.selected;
        NSString *answerStr = @"";
        for (int i = 0; i < [_dictioanry[@"list"][@"list"] count]; i++) {
            UIButton *button = [self viewWithTag:i + TAG_SelectButton];
            if (button.isSelected) {
                answerStr = [answerStr stringByAppendingFormat:@",%@", _dictioanry[@"list"][@"list"][i][@"option_name"]];
            }
        }
        // 判断是否都还开头，去掉
        if ([answerStr hasPrefix:@","]) {
            answerStr = [answerStr substringFromIndex:1];
        }
        [self.answerDictionary setObject:answerStr forKey:@"answer"];
    }
}

#pragma mark ============================= 简答题输入 ==============================
- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
    
    [self.answerDictionary setObject:textView.text forKey:@"answer"];
    
    return YES;
}

#pragma mark ============================= 拖动排序 ==============================
- (void)longGestureSortingOptionView:(UILongPressGestureRecognizer *)longGesture {
    
    CGPoint point = [longGesture locationInView:self];
//    NSLog(@"移动位置：%lf", point.y);
    
    if (longGesture.state == UIGestureRecognizerStateBegan) {
        // 开始长按
        _lastPoint = point;
        _contentSortView.sortSelect = NO;
        _contentSortView = (LPSortOptionView *)longGesture.view;
        _contentSortView.sortSelect = YES;
        [self bringSubviewToFront:_contentSortView];
        _contentOrigin = _contentSortView.frame.origin;
        [self resetViewChangeArrayIndex];
    }else if (longGesture.state == UIGestureRecognizerStateEnded) {
        // 松开
        CGRect tempFrame = _contentSortView.frame;
        tempFrame.origin = _contentOrigin;
        [UIView animateWithDuration:0.2 animations:^{
            _contentSortView.frame = tempFrame;
        } completion:^(BOOL finished) {
            _contentSortView.sortSelect = NO;
        }];
        _beforeSortView = nil;
        _afterSortView = nil;
        
        [self setSortAnswer];
        return;
    }
    
    // 拖动改变位置
    CGRect tempFrame = _contentSortView.frame;
    tempFrame.origin.x += point.x - _lastPoint.x;
    tempFrame.origin.y += point.y - _lastPoint.y;
    _contentSortView.frame = tempFrame;
    _lastPoint = point;
    NSInteger contentIndex = [_sortViewArray indexOfObject:_contentSortView];

    if (_contentSortView.frame.origin.y < _beforeOrigin.y && contentIndex > 0) {
        // 上拖下移
        _contentOrigin = _beforeOrigin;
        CGRect rect = _beforeSortView.frame;
        rect.origin.y = _beforeOrigin.y + CGRectGetHeight(_contentSortView.frame) + DSFixedPX(16);
        [UIView animateWithDuration:0.2 animations:^{
            _beforeSortView.frame = rect;
        }];
        
        NSLog(@"第%ld个和第%ld个交换", contentIndex, contentIndex - 1);
        [_sortViewArray exchangeObjectAtIndex:contentIndex withObjectAtIndex:contentIndex - 1];
        [self resetViewChangeArrayIndex];

    }else if (_contentSortView.frame.origin.y > _afterOrigin.y && contentIndex < _sortViewArray.count - 1) {
        // 下拖上移
        CGRect rect = _afterSortView.frame;
        rect.origin = _contentOrigin;
        [UIView animateWithDuration:0.2 animations:^{
            _afterSortView.frame = rect;
        }];
        _contentOrigin.y = _contentOrigin.y + _afterSortView.frame.size.height + DSFixedPX(16);
        
        NSLog(@"第%ld个和第%ld个交换", contentIndex, contentIndex + 1);
        [_sortViewArray exchangeObjectAtIndex:contentIndex withObjectAtIndex:contentIndex + 1];
        [self resetViewChangeArrayIndex];
    }
}

/** 交换数组元素位置，重置 */
- (void)resetViewChangeArrayIndex {
    
    for (int i = 0; i < _sortViewArray.count; i ++) {
        LPSortOptionView *optionView = _sortViewArray[i];
        if (_contentSortView == optionView) {
            if (i - 1 >= 0) {
                _beforeSortView = _sortViewArray[i - 1];
                _beforeOrigin = _beforeSortView.frame.origin;
            }
            if (i + 1 < _sortViewArray.count) {
                _afterSortView = _sortViewArray[i + 1];
                _afterOrigin = _afterSortView.frame.origin;
            }
            break;
        }
    }
}

- (void)setSortAnswer {
    
    NSString *answerStr = @"";
    for (int i = 0; i < _sortViewArray.count; i ++ ) {
        LPSortOptionView *optionView = _sortViewArray[i];
        NSInteger index = optionView.tag - TAG_SortView;
        if (index >= 0 && index < [_dictioanry[@"list"][@"list"] count]) {
            answerStr = [answerStr stringByAppendingFormat:@",%@", _dictioanry[@"list"][@"list"][index][@"option_name"]];

        }
    }
    // 判断是否都还开头，去掉
    if ([answerStr hasPrefix:@","]) {
        answerStr = [answerStr substringFromIndex:1];
    }
    [self.answerDictionary setObject:answerStr forKey:@"answer"];
}



#pragma mark ============================= 填充数据 ==============================
- (void)fillContent {
    
    NSString *answerStr = [NSString stringWithFormat:@"%@", _dictioanry[@"list"][@"right_answer"]];
    
    if (answerStr.length <= 0 || [_dictioanry[@"list"][@"right_answer"] isKindOfClass:[NSNull class]]) {
        return;
    }
    
    // 解析回答字符串，转数组
    NSArray *answerArray;
    if (answerStr.length > 1) {
        answerArray = [answerStr componentsSeparatedByString:@","];
    }else {
        answerArray = [NSArray arrayWithObject:answerStr];
    }
    
    if (self.questionType == questionType_singleChoice || self.questionType == questionType_multipleChoie) {
        // 单选/多选
        for (int i = 0; i < answerArray.count; i ++) {
            for (int j = 0; j < [_dictioanry[@"list"][@"list"] count]; j ++) {
                NSString *answer = answerArray[i];
                NSString *optionStr = _dictioanry[@"list"][@"list"][j][@"option_name"];
                if ([answer isEqualToString:optionStr]) {
                    _selectButton = [self viewWithTag:TAG_SelectButton + j];
                    // 赋值
                    [self selectButtonClick:_selectButton];
                }
            }
        }
        
    }else if (self.questionType == questionType_sortingProblem) {
        // 排序
        /** 填充改变顺序（上次提交顺序） */
        [self fillChangeSortOptionArray:answerArray];
    }else if (self.questionType == questionType_shortAnswer) {
        // 简答
        _textView.text = answerStr;
        [self.answerDictionary setObject:answerStr forKey:@"answer"];
    }
}

/** 填充改变顺序（上次提交顺序） */
- (void)fillChangeSortOptionArray:(NSArray *)answerArray {
    
    if (answerArray.count != [_dictioanry[@"list"][@"list"] count]) {
        return;
    }
    
    _sortViewArray = [NSMutableArray array];
    _offsetY = CGRectGetMaxY(_titleLabel.frame);
    
    for (int i = 0; i < answerArray.count; i ++) {
        NSString *string = answerArray[i];
        NSInteger index = [string characterAtIndex:0] - 65;
        LPSortOptionView *optionView = [self viewWithTag:TAG_SortView + index];
        CGRect rect = optionView.frame;
        rect.origin.y = _offsetY + DSFixedPX(20);
        optionView.frame = rect;
        [_sortViewArray addObject:optionView];
        _offsetY = CGRectGetMaxY(optionView.frame);
    }
}

@end
